package com.scujcc.diandiantv;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.net.NetworkRequest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private RecyclerView channelRv;
    public static final String TAG = "MAIN";

    final Handler h = new Handler() {
        //当收到消息时，应该执行的代码
        @Override
        public void handleMessage(Message msg) {
            Channel m = (Channel) msg.obj;
            Toast.makeText(MainActivity.this,
                    "频道名称："+m.getName()
                        +"频道desc:"+m.getDesc(),
                    Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        testHandler();

        testChannel();
//        this.channelRv = findViewById(R.id.channel_rv);
//        ChannelRvAdapter adapter = new ChannelRvAdapter();
//        this.channelRv.setAdapter(adapter);
//        this.channelRv.setLayoutManager(new LinearLayoutManager(this));
    }

    private void testChannel() {
        ChannelApi api = NetworkFactory.getChannelApi();
        Call<Channel> c = api.getChannel("60b5de400decdf3948840f9e");
        c.enqueue(new Callback<Channel>() {
            @Override
            public void onResponse(Call<Channel> call, Response<Channel> response) {
                Channel ch = response.body();
                Log.d(TAG, "频道名称：" + ch.getDesc());
                Log.d(TAG, "频道缩写：" + ch.getName());
                Message msg = new Message();
                msg.obj = ch;
                h.sendMessage(msg);
            }

            @Override
            public void onFailure(Call<Channel> call, Throwable t) {
                Log.e(TAG,"网络出错！", t);
            }
        });
        Log.d(TAG, "Hello world");
    }

    private void testHandler() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                //子线程的任务代码，例如访问网络
                //假设网络返回数据Hello
                String result = "Hello";
                Message msg = new Message();
                msg.obj = result;
                h.sendMessage(msg);
            }
        };
        LinkedBlockingQueue queue = new LinkedBlockingQueue();
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,
                10,
                50,
                TimeUnit.MILLISECONDS, queue);
        pool.execute(r);

    }
}